<?php

namespace App\Http\Controllers\Api\Merchant;

use App\Enterprise;
use App\EnterpriseUser;
use App\Http\Services\CommonManager;
use App\Http\Services\MerchantManager;
use App\Http\Services\UserManager;
use App\User;
use App\UserInfo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 获取用户列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page           = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $keyword        = $request->get('keyword') ?? '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];

        /** @var User $user */
        $users = User::whereEnterpriseId($enterpriseInfo->id);

        if ($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')->orWhere('realname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $users->whereIn('id',$nickname)->orWhere('phone','like','%'.trim($keyword).'%');
        }
        $pageInfo['total']=$users->count();

        $users = $users->whereRole(0)->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        foreach ($users as $user){
            $temp_user_info = CommonManager::getUserBasicInfo($user->id);
            $user->user_info = $temp_user_info ? $temp_user_info : [];
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);
    }

    /**
     * 用户详情
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $userInfo = CommonManager::getUserBasicInfo($id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userInfo]);
    }
}
